/*******************************************************************************
 * Developer: Ian Doyle
 * Date:      6/23/2012
 *
 * All code Copyright (C) 2012 Ian Doyle. All rights reserved.
 *
 * This file is a part of FileFocus.
 *
 * FileFocus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FileFocus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FileFocus.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/


package filefocus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;

import filefocus.exception.FailedExecutionException;
import filefocus.exception.UnreadableFileException;

public class GrowableTreeBranch<T extends FileOrganizationTreeBranch> implements FileOrganizationTreeBranch {
	
	private File leaf;
	private T branch;
	
	public GrowableTreeBranch(T branch) {
		this.leaf = null;
		this.branch = branch;
	}

	@Override
	public void addFile(File file) throws FileNotFoundException, IOException,
			UnreadableFileException, FailedExecutionException,
			InterruptedException, NoSuchAlgorithmException {
		if(branch.count() == 0) {
			if(leaf == null) {
				leaf = file;
			}
			else {
				branch.addFile(leaf);
				leaf = null;
				branch.addFile(file);
			}
		}
		else {
			branch.addFile(file);
		}
	}
	
	public int count() {
		if(leaf == null)
			return branch.count();
		else
			return 1;
	}

	public T getBranch() {
		return branch;
	}

	@Override
	public Collection<FileList> flatten() {
		if(leaf == null)
		{
			return branch.flatten();
		}
		else
		{
			FileList list = new FileList();
			list.add(leaf);
			return list.flatten();
		}
	}
}
